package ru.spbau.krasko.phonelock.main;

import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.container.MainScreen;
import ru.spbau.krasko.phonelock.dynamic.DynamicField;
import ru.spbau.krasko.phonelock.utils.Constants;

public class DynamicFieldContainer extends MainScreen {
	
	private volatile DynamicField handling = null;
	
	public void paint(final Graphics g) {
		g.setColor(0x0);
		g.fillRect(0, 0, Constants.SCREEN_W, Constants.SCREEN_H);
		DynamicField.paintAll(g);
		super.subpaint(g);
	}

	protected boolean touchEvent(TouchEvent msg) {
		final int x = msg.getX(1);
		final int y = msg.getY(1);

		if (msg.getEvent() == TouchEvent.DOWN) {
			handling = DynamicField.getFieldAt(x, y, handling);			
			if (handling != null) {
				handling.setDesiredPos(x, y);
				handling.setHanged(true);
			}
		}

		if (msg.getEvent() == TouchEvent.MOVE && handling != null) {
			handling.setDesiredPos(x, y);
		}

		if (msg.getEvent() == TouchEvent.UP) {
			if (handling != null) {
				DynamicField target = DynamicField.getFieldAt(x, y, handling);
				if(target != null) {
					target.initInteraction(handling);
				}
				handling.setHanged(false);
				handling.returnToOrigin(false);
				handling = null;
			}
		}
		return true;
	}
	
	

	public DynamicFieldContainer() {
	}
}
